from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet, ModelViewSet

from day02_books import models, Ser


# Create your views here.
#登录部分
class LoginView(ViewSet):
    def login(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        if username is not None and password is not None:
            try:
                data = models.LoginAdmin.objects.get(username=username)
                if data.password == password:
                    datainfo = {
                        "username":data.username,
                        "password":data.password
                    }
                    return Response({'status':200,'message':'登录成功',"data":datainfo})
                else:
                    return Response({'status':400,'message':'用户名或密码错误'})
            except:
                return Response({'status':400,'message':'用户名或密码错误'})

        else:
            return Response({'status':400,'message':'用户名或密码不能为空'})
class MyPage(PageNumberPagination):
    page_size = 5
    page_size_query_param = 'size'
    page_query_param = 'page'
    max_page_size = 100

class BookView(ModelViewSet):
    queryset = models.BookInfo.objects.all()
    serializer_class = Ser.BookSerializer
    pagination_class = MyPage
    lookup_field = 'id'
    lookup_url_kwarg = 'id'
    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get('name')
        book_type = self.request.query_params.get('book_type')
        if name:
            queryset = queryset.filter(name__contains=name)
        if book_type:
            queryset = queryset.filter(book_type_id=book_type)
        queryset = queryset.filter(disable=False)
        return queryset
    @action(methods=['post'],detail=False)
    def add_book(self,request):
        name = request.data.get('name')
        author = request.data.get('author')
        ISBN = request.data.get('ISBN')
        book_type_id = request.data.get('book_type_id')
        models.BookInfo.objects.create(name=name,author=author,ISBN=ISBN,book_type_id=book_type_id)
        return Response({'status':200,'message':'添加成功'})
    @action(methods=['delete'],detail=True)
    def delete_book(self,request,id):
        models.BookInfo.objects.filter(id=id).update(disable=True)
        return Response({'status':200,'message':'删除成功'})

    def update(self, request, *args, **kwargs):

        return super().update(request, *args, **kwargs)


class BookTypeView(ModelViewSet):
    queryset = models.BookType.objects.all()
    serializer_class = Ser.BookTypeSerializer
    lookup_field = 'id'
    lookup_url_kwarg = 'id'
